package com.emo.wowoblog.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.emo.wowoblog.dao.UsersDao;
import com.emo.wowoblog.entity.Users;
import com.emo.wowoblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UsersDao usersDao;

    @Override
    public void reg(Users user) {
        user.setPassword(DigestUtil.bcrypt(user.getPassword()));
        usersDao.save(user);
    }

    @Override
    public Users login(String email, String password) {
        Users byEmail = usersDao.findByEmail(email);
        if(null == byEmail) {
            return null;
        }
        // 判断密码是否是密文
        if(password.contains("$")) {
            // 密文直接对比数据库中的密文进行身份验证
            if(byEmail.getPassword().equals(password)) {
                return byEmail;
            }
        } else {
            if(DigestUtil.bcryptCheck(password, byEmail.getPassword())) {
                return byEmail;
            }
        }
        return null;
    }

    @Override
    public boolean isExistEmail(String email) {

        return usersDao.findByEmail(email) != null;
    }

}
